//
//  MainSecondViewController.m
//  Beauty
//
//  Created by Snow on 16/9/3.
//  Copyright © 2016年 Snow. All rights reserved.
//

#import "MainSecondViewController.h"
#import "MainSecondTableViewCell.h"
#import "SecondTableViewCell.h"
#import "GXMacro.h"
#import "GXNetWorkingParser.h"
#import "ModelOfSecondTableView.h"
#import "UIView+Frame.h"
#import "ViewControllerOfHotWindow.h"
#import "ModelOfDetailWindow.h"
#import "LoginViewController.h"
@interface MainSecondViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *array;
@property (nonatomic, strong) UIImageView *image;
@property (nonatomic, strong) UIButton *buttonOfCover;
@property (nonatomic, strong) UIButton *buttonOfInspiration;
@property (nonatomic, strong) UIView *viewOfButton;
@property (nonatomic, strong) UITapGestureRecognizer *tap;
@property (nonatomic, strong) NSString *personal_id;
@end

@implementation MainSecondViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
    self.tabBarController.tabBar.hidden = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self handleData];
    [self createView];
}
- (void)createFresh
{
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
    }];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(handleLoadNewData)];
}
- (void)handleLoadNewData {
    //请求服务器更新数据
    [GXNetWorkingParser GETWithURL:@"http://www.wantease.com/api/index.php?act=micro&op=get_personal_list_wap_1_5&curpage=1&page=5" par:nil success:^(id responseObject) {
        NSDictionary *dic = [responseObject objectForKey:@"datas"];
        NSArray *arr = [dic objectForKey:@"goods_list"];
        NSMutableArray *arrOfNew = [NSMutableArray array];
        for (NSDictionary *dictionary in arr) {
            ModelOfSecondTableView *model = [[ModelOfSecondTableView alloc] init];
            [model setValuesForKeysWithDictionary:dictionary];
            [arrOfNew addObject:model];
        }
        NSRange range = NSMakeRange(0, arrOfNew.count);
        NSIndexSet *set = [NSIndexSet indexSetWithIndexesInRange:range];
        [_array insertObjects:arrOfNew atIndexes:set];
        [_tableView reloadData];
    } filed:^(NSError *error) {
    }];
    [self.tableView.mj_header endRefreshing];
}
- (void)createView
{
    self.navigationController.navigationBar.translucent = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 30)];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 140, 30)];
    label.text = @"瞬间 Inspiration";
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont systemFontOfSize:18];
    [view addSubview:label];
    label.textAlignment = 2;
    self.image = [[UIImageView alloc] initWithFrame:CGRectMake(150, 10, 15, 15)];
    self.image.image = [UIImage imageNamed:@"下拉"];
    [view addSubview:self.image];
    self.tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapTitleView:)];
    [view addGestureRecognizer:self.tap];
    self.navigationItem.titleView = view;
    
    //搜索按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemCamera target:self action:@selector(search:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"box"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(box:)];
    
    self.navigationController.navigationBar.translucent = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 49) style:UITableViewStyleGrouped];
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerClass:[MainSecondTableViewCell class] forCellReuseIdentifier:@"MainSecondTableViewCell"];
    [_tableView registerClass:[SecondTableViewCell class] forCellReuseIdentifier:@"SecondTableViewCell"];
    [self createFresh];
}
//封面更换
- (void)tapTitleView:(UITapGestureRecognizer *)tap
{
    self.viewOfButton = [[UIView alloc] initWithFrame:CGRectMake(0, -60, SCREEN_WIDTH, 60)];
    self.buttonOfCover = [UIButton buttonWithType:UIButtonTypeSystem];
    self.buttonOfInspiration = [UIButton buttonWithType:UIButtonTypeSystem];
    _buttonOfCover.backgroundColor = [UIColor whiteColor];
    _buttonOfInspiration.backgroundColor = [UIColor whiteColor];
    _buttonOfInspiration.tintColor = [UIColor lightGrayColor];
    _buttonOfCover.tintColor = [UIColor blackColor];
    self.buttonOfCover.frame = CGRectMake(0, 0, SCREEN_WIDTH, 30);
    [_buttonOfCover addTarget:self action:@selector(changeToCover:) forControlEvents:UIControlEventTouchUpInside];
    [_buttonOfInspiration addTarget:self action:@selector(changeToInspiration:) forControlEvents:UIControlEventTouchUpInside];
    [self.viewOfButton addSubview:self.buttonOfCover];
    [self.buttonOfCover setTitle:@"封面 Cover" forState:UIControlStateNormal];
    self.buttonOfInspiration.frame = CGRectMake(0, 30.5, SCREEN_WIDTH, 30);
    [self.viewOfButton addSubview:self.buttonOfInspiration];
    [self.buttonOfInspiration setTitle:@"瞬间 Inspiration" forState:UIControlStateNormal];
    [self.view addSubview:self.viewOfButton];
    [UIView animateWithDuration:0.5 animations:^{
        _image.image = [UIImage imageNamed:@"上拉"];
        self.viewOfButton.x_y = 0;
    }];
    [tap removeTarget:self action:@selector(tapTitleView:)];
    [tap addTarget:self action:@selector(backToTitle:)];
}
- (void)backToTitle:(UIGestureRecognizer *)back
{
    [back removeTarget:self action:@selector(backToTitle:)];
    [back addTarget:self action:@selector(tapTitleView:)];
    [UIView animateWithDuration:0.5 animations:^{
        _image.image = [UIImage imageNamed:@"下拉"];
        self.viewOfButton.x_y = -60;
    }];
    
}
- (void)changeToCover:(UIButton *)button
{
    _buttonOfCover.tintColor = [UIColor lightGrayColor];
    _buttonOfInspiration.tintColor = [UIColor blackColor];
    [UIView animateWithDuration:0.5 animations:^{
        _image.image = [UIImage imageNamed:@"上拉"];
        self.viewOfButton.x_y = -60;
    }];
    [self.tap removeTarget:self action:@selector(backToTitle:)];
    [self.tap addTarget:self action:@selector(tapTitleView:)];
    [self.navigationController popViewControllerAnimated:NO];
}
- (void)changeToInspiration:(UIButton *)button
{
    _buttonOfCover.tintColor = [UIColor blackColor];
    _buttonOfInspiration.tintColor = [UIColor lightGrayColor];
    [UIView animateWithDuration:0.5 animations:^{
        _image.image = [UIImage imageNamed:@"上拉"];
        self.viewOfButton.x_y = -60;
    }];
    [self.tap removeTarget:self action:@selector(backToTitle:)];
    [self.tap addTarget:self action:@selector(tapTitleView:)];
}
- (void)search:(UIBarButtonItem *)barButtonItem
{
    
}
//按钮
- (void)box:(UIBarButtonItem *)barButtonItem
{
    
}
- (void)handleData
{
    _array = [NSMutableArray array];
    [GXNetWorkingParser GETWithURL:@"http://www.wantease.com/api/index.php?act=micro&op=get_personal_list_wap_1_5&curpage=1&page=5" par:nil success:^(id responseObject) {
    NSDictionary *dic = [responseObject objectForKey:@"datas"];
    NSArray *arr = [dic objectForKey:@"goods_list"];
    for (NSDictionary *dictionary in arr) {
        ModelOfSecondTableView *model = [[ModelOfSecondTableView alloc] init];
        [model setValuesForKeysWithDictionary:dictionary];
        [_array addObject:model];
    }
        [_tableView reloadData];
} filed:^(NSError *error) {
    
}];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _array.count + 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        MainSecondTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MainSecondTableViewCell"];
        return cell;
    } else {
        SecondTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SecondTableViewCell"];
        ModelOfSecondTableView *model = [_array objectAtIndex:indexPath.section - 1];
//        cell.labelOfName.text = model.member_name;
//        cell.labelOfName.font = [UIFont systemFontOfSize:14];
//        cell.widthBlock = ^(CGFloat height){
//            CGRect newRect = [model.member_name boundingRectWithSize:CGSizeMake(0, height) options:1 attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14]} context:nil];
//            CGFloat width = ceilf(newRect.size.width);
//            return width;
//        };
//        [cell.imageOfPerson sd_setImageWithURL:[NSURL URLWithString:model.member_avatar]];
        [cell.imageOfContent sd_setImageWithURL:[NSURL URLWithString:model.commend_image]];
        return cell;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        return 0;
    } else {
        return 150;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        return nil;
    } else {
        ModelOfSecondTableView *model = [_array objectAtIndex:section - 1];
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 150)];
        view.backgroundColor = [UIColor whiteColor];
        UILabel *labelOfContent = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, SCREEN_WIDTH - 220, 50)];
        [view addSubview:labelOfContent];
        labelOfContent.numberOfLines = 0;
        labelOfContent.text =model.commend_message;
        labelOfContent.font = [UIFont systemFontOfSize:12];
        NSArray *arrayOfButton = model.micro_like_data;
        for (int i = 0; i < arrayOfButton.count; i++) {
            NSDictionary *dic = [arrayOfButton objectAtIndex:i];
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            [view addSubview:button];
            button.layer.masksToBounds = YES;
            button.layer.cornerRadius = 20;
            [button setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:model.commend_image]]] forState:UIControlStateNormal];
            [button setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[dic objectForKey:@"member_avatar"]]]] forState:UIControlStateNormal];
            button.frame = CGRectMake(SCREEN_WIDTH - (i + 1) * 30 - 20, 20, 40, 40);
        }
        UIView *viewOfLine = [[UIView alloc] initWithFrame:CGRectMake(10, 70, SCREEN_WIDTH - 20, 1)];
        [view addSubview:viewOfLine];
        viewOfLine.backgroundColor = [UIColor lightGrayColor];
        UIImageView *imageOfPerson = [[UIImageView alloc] initWithFrame:CGRectMake(10, 90, 50, 50)];
        [imageOfPerson sd_setImageWithURL:[NSURL URLWithString:model.member_avatar]];
        imageOfPerson.layer.masksToBounds = YES;
        imageOfPerson.layer.cornerRadius = 25;
        [view addSubview:imageOfPerson];
        //关注button
        UIButton *buttonOfContract = [UIButton buttonWithType:UIButtonTypeSystem];
        buttonOfContract.frame = CGRectMake(70, 110, 60, 30);
        buttonOfContract.layer.masksToBounds = YES;
        buttonOfContract.layer.cornerRadius = 5;
        buttonOfContract.layer.borderColor = [[UIColor colorWithRed:0.945 green:0.325 blue:0.549 alpha:1.000] CGColor];
        buttonOfContract.layer.borderWidth = 1;
        [view addSubview:buttonOfContract];
        [buttonOfContract setTitle:@"+关注" forState:UIControlStateNormal];
        buttonOfContract.tintColor = [UIColor colorWithRed:0.945 green:0.325 blue:0.549 alpha:1.000];
        [buttonOfContract addTarget:self action:@selector(handleContiontract:) forControlEvents:UIControlEventTouchUpInside];
        _personal_id = model.commend_member_id;
        
        //nameLabel
        UILabel *labelOfName = [[UILabel alloc] initWithFrame:CGRectMake(70, 85, 80, 20)];
        [view addSubview:labelOfName];
        labelOfName.text = model.member_truename;
        labelOfName.font = [UIFont systemFontOfSize:15];
        UIButton *buttonOfLike = [UIButton buttonWithType:UIButtonTypeCustom];
        buttonOfLike.frame = CGRectMake(180, 95, 30, 30);
        [view addSubview:buttonOfLike];
        [buttonOfLike setImage:[UIImage imageNamed:@"buttonOfLove"] forState:UIControlStateNormal];
        
        UILabel *labelOfLikeCount = [[UILabel alloc] initWithFrame:CGRectMake(220, 95, 30, 30)];
        [view addSubview:labelOfLikeCount];
        labelOfLikeCount.text = model.like_count;
        labelOfLikeCount.textColor = [UIColor lightGrayColor];
        UIButton *buttonOfShare = [UIButton buttonWithType:UIButtonTypeCustom];
        buttonOfShare.frame = CGRectMake(260, 90, 30, 30);
        [buttonOfShare setImage:[UIImage imageNamed:@"buttonOfShares"] forState:UIControlStateNormal];
        [view addSubview:buttonOfShare];
        
        UIButton *buttonOfFile = [UIButton buttonWithType:UIButtonTypeCustom];
        buttonOfFile.frame = CGRectMake(320, 92, 30, 30);
        [buttonOfFile setImage:[UIImage imageNamed:@"buttonOfFlies"] forState:UIControlStateNormal];
        [view addSubview:buttonOfFile];
        return view;
    }
}
- (void)handleContiontract:(UIButton *)button
{
    //获取UserDefault
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSString *name = [userDefault objectForKey:@"name"];
    NSString *password = [userDefault objectForKey:@"password"];
    if (name == nil)
    {
        LoginViewController *login = [[LoginViewController alloc] init];
        NSLog(@"%@",name);
[self presentViewController:login animated:YES completion:^{
    
}];
        self.tabBarController.tabBar.hidden = YES;
        self.navigationController.navigationBar.hidden = YES;
    } else {
        NSString *url = [NSString stringWithFormat:@"http://www.wantease.com/mobile1/index.php?act=sns_friend&op=add_follow&key=%@&member_id=%@", password, _personal_id];
        [GXNetWorkingParser GETWithURL:url par:nil success:^(id responseObject) {
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"已关注" message:@"" preferredStyle:UIAlertControllerStyleAlert];
            
            // 出现
            [self presentViewController:alertController animated:YES completion:^{
                
            }];
            // 移除
            [alertController dismissViewControllerAnimated:YES completion:^{
            }];
            [_tableView reloadData];
        } filed:^(NSError *error) {
            
        }];
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        
        return 100;
    } else {
        return 300;
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ModelOfSecondTableView *model = [_array objectAtIndex:indexPath.section - 1];
    ViewControllerOfHotWindow *view = [[ViewControllerOfHotWindow alloc] init];
    self.tabBarController.tabBar.hidden = YES;
        view.person_id = model.personal_id;
    UIBarButtonItem *barItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:nil action:nil];
    self.navigationItem.backBarButtonItem = barItem;
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.navigationController pushViewController:view animated:YES];
}
@end
